//
//  HomeViewController.m
//  SelfDriving
//
//  Created by apple on 15/12/1.
//  Copyright © 2015年 apple. All rights reserved.
//

#import "HomeViewController.h"
#import "SDCycleScrollView.h"
#import "MemberRoamingCell.h"
#import "BusinessService+FJ.h"
#import "FJModel.h"
#import "FriendDetailsMainVC.h"
#import "QryResultViewController.h"
#import "UIImage+FEBoxBlur.h"
#import "SceneViewController.h"
#import "JHHeaderFlowLayout.h"
#import "XhwWebViewController.h"
//黑白
const float heis[] = {
    0.8f,  1.6f, 0.2f, 0, -163.9f,
    0.8f,  1.6f, 0.2f, 0, -163.9f,
    0.8f,  1.6f, 0.2f, 0, -163.9f,
    0,  0, 0, 1.0f, 0 };

@interface HomeViewController ()<SDCycleScrollViewDelegate,BaseCollectionDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *adView;
@property (weak, nonatomic) IBOutlet BaseCollection *collection;
@property (weak, nonatomic) IBOutlet UIView *zhibView;
@property (nonatomic, copy) NSArray *colorArr;
@property (weak, nonatomic) IBOutlet JHHeaderFlowLayout *layout;
@property(nonatomic,assign)NSInteger count;

@end

@implementation HomeViewController{
    NSArray *addata;
    UILabel *notlabel;
    NSMutableArray *data;
    NSMutableArray *datas;
    
    UIView *zbview;//直播view
    
    NSMutableDictionary *ndic;
    UITableView *table;
    int isdel;
}

-(void)viewWillAppear:(BOOL)animated{
    _zhibView.hidden = NO;
    self.navigationController.navigationBarHidden = NO;
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(scollTop:)
     name:@"scollTop"
     object:nil];
}

static NSString *const headerId = @"headerId";
static NSString *const footerId = @"footerId";


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    /*改：设置首页header悬停效果相关步骤
     1.导入JHHeaderFlowLayout文件
     2.将对应storyBoard中的collection控件中的属性layout设置为自定义的JHHeaderFlowLayout
     */
//    _layout.itemSize = CGSizeMake((SCRE_WIDTH)/2-0.5, (SCRE_WIDTH-10)/2-1);
    
//    _layout.sectionInset = UIEdgeInsetsMake(10, 0, 0, 0);
    
    self.layout.minimumLineSpacing = 1;
    self.layout.minimumInteritemSpacing = 0.5;
    
    _count=3;
    ndic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    
    CGRect co =  _collection.frame;
    co.origin.y = 64;
//    co.size.height = SCRE_HEIGHT - 50 - 65;
    co.size.height = SCRE_HEIGHT - 49 - 64;
    _collection.frame = co;
    
    _collection.bdelegate = self;
    data = [[NSMutableArray alloc]init];
    datas = [[NSMutableArray alloc]init];
    self.automaticallyAdjustsScrollViewInsets = NO;//处理UICollectionView预留空白
    _zhibView.alpha = 0.7;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//    [dic setObject:@"0" forKey:@"action"];xhw11月20号改
    [dic setObject:@"0" forKey:@"type"];
    [[BusinessService shareInstance]getADlist:dic success:^(id result) {
        NSMutableArray *qry = result;
        //当请求到的广告为空是就不显示广告栏(xhw11月3日改)
        if (qry.count == 0) {
            [[NSNotificationCenter defaultCenter]postNotificationName:@"deleteAD" object:nil];
        }
        else {
            NSMutableArray *datas = [[NSMutableArray alloc]init];
            for (int i=0 ; i<qry.count; i++) {
                FJModel *msg = [qry objectAtIndex:i];
                [datas addObject:msg.img];
            }
            addata = qry;
            
            
            //网络加载 --- 创建带标题的图片轮播器
            SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCRE_WIDTH ,_adView.frame.size.height) imageURLStringsGroup:datas]; // 模拟网络延时情景
            cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
            cycleScrollView2.delegate = self;
            cycleScrollView2.dotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
            //xhw2018-1-12改bug11576:之前是灰色的原因主要是placeholder没找到
            //cycleScrollView2.placeholderImage = [UIImage imageNamed:@"placeholder"];
            cycleScrollView2.placeholderImage = [UIImage imageNamed:@"pc_circle_placeholder"];
            [_adView addSubview:cycleScrollView2];
            
            UIButton *imgbtn = [[UIButton alloc]initWithFrame:CGRectMake(SCRE_WIDTH - 40, (64/2-15/2), 15, 15)];
            [imgbtn setImage:[UIImage imageNamed:@"delete_d.png"] forState:UIControlStateNormal];
            [_adView addSubview:imgbtn];

        }
        
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
    [_collection registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerId];
    
    
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(qryActions:)
     name:@"qryAction"
     object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(deleteAD:)
     name:@"deleteAD"
     object:nil];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(toVipCenteVC:)
     name:@"toVipCenteVC"
     object:nil];
   
    [self configLoadData];
}
-(void)scollTop:(NSNotification *)not{
    if (data.count!=0) {
        [_collection scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
                            atScrollPosition:UICollectionViewScrollPositionTop
                                    animated:YES];
    }
}
-(void)toVipCenteVC:(NSNotification *)not {
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"GR"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"VipCenteVC"];
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
-(void)configLoadData {
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
//    [dic setObject:@"0" forKey:@"action"];
    [dic setObject:@"0" forKey:@"type"];
    [[BusinessService shareInstance]getADlist:[dic mutableCopy] success:^(id result) {
        NSMutableArray *qry = result;
        NSMutableArray *datas = [[NSMutableArray alloc]init];
        for (int i=0 ; i<qry.count; i++) {
            FJModel *msg = [qry objectAtIndex:i];
            [datas addObject:msg.img];
        }
        addata = qry;
        //网络加载 --- 创建带标题的图片轮播器
        SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, SCRE_WIDTH ,_adView.frame.size.height) imageURLStringsGroup:datas]; // 模拟网络延时情景
        cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        cycleScrollView2.delegate = self;
        cycleScrollView2.dotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
        //xhw2018-1-12改bug11576:之前是灰色的原因主要是placeholder没找到
        //cycleScrollView2.placeholderImage = [UIImage imageNamed:@"placeholder"];
        cycleScrollView2.placeholderImage = [UIImage imageNamed:@"pc_circle_placeholder"];
        [_adView addSubview:cycleScrollView2];
        
        UIButton *imgbtn = [[UIButton alloc]initWithFrame:CGRectMake(SCRE_WIDTH - 40, (64/2-15/2), 15, 15)];
        [imgbtn setImage:[UIImage imageNamed:@"delete_d.png"] forState:UIControlStateNormal];
        [_adView addSubview:imgbtn];
        
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}
#pragma mark 附近人查询结果
-(void)qryActions:(NSNotification *)not {
    ndic = [[NSMutableDictionary alloc]init];
    [ndic addEntriesFromDictionary:[UserDefaults readUserDefaultObjectValueForKey:@"userLocation"]];
    [ndic addEntriesFromDictionary:not.object];
//    [_collection Refresh];
    //xhw11月8号改
//    [self initData:0];
    [self initData:1];
}

#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)indexs
{
    FJModel *model = [addata objectAtIndex:indexs];
//    SVWebViewController *webC = [[SVWebViewController alloc] initWithAddress:model.url];
//    webC.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:webC animated:YES];
   
    XhwWebViewController * web = [[XhwWebViewController alloc]init];
    web.urlString = model.url;
    web.ADid = model.id;
    web.title = @"主页广告";
    web.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:web animated:YES];
}
-(void)initData:(int)index{
    [ndic setObject:[NSNumber numberWithInt:index] forKey:@"page"];
    [[BusinessService shareInstance] nearby:ndic success:^(id result) {
        //         datas = [_collection result:result olddata:datas index:index];
        datas = result;
        LoginResponseModel *model = [datas firstObject];
        if (index == 1) {
            [data removeAllObjects];
        }
        [data addObjectsFromArray:model.personlist];
        if (notlabel) {
            [notlabel removeFromSuperview];
        }
        notlabel = (UILabel *)[_collection notData];
        if (data.count == 0) {
            [self.view addSubview:notlabel];
        }
        [_collection reloadData];
        [self zhiboView];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}

#pragma mark 直播View
-(void)zhiboView{
    if (zbview) {
        [zbview removeFromSuperview];
    }
    zbview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCRE_WIDTH, 54)];
    zbview.tag = 1991;
    zbview.backgroundColor = [UIColor whiteColor];
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 90, 30)];
    lable.text = @"快拍现场";
    lable.font = [UIFont systemFontOfSize:14];
    
    UILabel *lable1 = [[UILabel alloc]initWithFrame:CGRectMake(10, 20, 150, 30)];
    lable1.text = @"正在播放的现场";
    lable1.font = [UIFont systemFontOfSize:14];
    lable1.textColor = [UIColor grayColor];
    
    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCRE_WIDTH, 54)];
    [btn addTarget:self action:@selector(Tozhibo:) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:[UIImage imageNamed:@"next"] forState:UIControlStateNormal];
    btn.imageEdgeInsets = UIEdgeInsetsMake(0, SCRE_WIDTH-20, 0, 0);
    [zbview addSubview:btn];
    [zbview addSubview:lable];
    [zbview addSubview:lable1];
    
    LoginResponseModel *model = [datas firstObject];
    NSMutableArray *ary = [model.xianchanglist objectForKey:@"headlist"];
    if (ary.count>3) {
        [NSTimer scheduledTimerWithTimeInterval:5.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
            int h =  SCRE_WIDTH - 65;
            for (int i = _count; i<_count+3; i ++) {
                UIImageView  *img = [[UIImageView alloc]initWithFrame:CGRectMake(h, 54/2-20, 40, 40)];
                if (i==ary.count) {
                    [timer invalidate];
                    break;
                }
                [ValidateHelper setImage:[ary objectAtIndex:i] img:img istoux:YES];
                img.layer.cornerRadius = 20;
                img.clipsToBounds = YES;
                [zbview addSubview:img];
                h = h - 45;
                _count = _count++;
            }
        }];
    }else {
        int h =  SCRE_WIDTH - 65;
        for (int i = 0; i<ary.count; i++) {
            UIImageView  *img = [[UIImageView alloc]initWithFrame:CGRectMake(h, 54/2-20, 40, 40)];
            [ValidateHelper setImage:[ary objectAtIndex:i] img:img istoux:YES];
            img.layer.cornerRadius = 20;
            img.clipsToBounds = YES;
            [zbview addSubview:img];
            h = h - 45;
        }
    }
//    zbview.alpha = 0.7;
    [_zhibView addSubview:zbview];
}
-(void)Tozhibo:(UIButton *)btn{
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"SceneKPViewVC"];
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
    
    
}
-(void)viewWillDisappear:(BOOL)animated{
    _zhibView.hidden = YES;
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"scollTop" object:nil];

}

#pragma mark collectionViewDelegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)sectio{
    return data.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MemberRoamingCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MemberRoamingCell" forIndexPath:indexPath];
    
    NSMutableDictionary *dic = [data objectAtIndex:indexPath.row];
    LoginResponseModel *model = [[LoginResponseModel alloc]init];

    [model serializationWithDictionary:dic];
    
//    cell.name_label.text = model.nickname;
    NSString *job = model.job;
    NSString *age = [NSString stringWithFormat:@"%@岁",[ValidateHelper timeToAge:model.age]];
    cell.name_label.font = [UIFont systemFontOfSize:13];
    cell.name_label.text = [NSString stringWithFormat:@"%@  %@ %@",model.nickname,age,job];
    
    
//    [cell.head_img sd_setImageWithURL:Url(model.headlarge) placeholderImage:[UIImage imageWithColor:UIColorMakeWithHex(colorHex)]];
    //    [ValidateHelper setImage:model.headlarge img:cell.head_img istoux:NO];
    
    
    
    //xhw2018-2-28改
//    [cell.head_img sd_setImageWithURL:Url(model.headlarge) placeholderImage:[UIImage imageWithColor:[UIColor whiteColor]]];
    [cell.head_img sd_setImageWithURL:Url(model.headlarge) placeholderImage:[UIImage imageNamed:@"notimgs"]];
    

    NSString *distance = [ValidateHelper DistanceFormat:model.distance];
    NSString *createTime = [ValidateHelper distanceTimeWithBeforeTime:[model.createtime doubleValue]];
//    cell.sign_lable.text = [NSString stringWithFormat:@"%@ %@ %@",age,job,distance,createTime];
    cell.sign_lable.font = [UIFont systemFontOfSize:11];
    cell.sign_lable.text = [NSString stringWithFormat:@"%@  %@",distance,createTime];
    if([model.memberlevel intValue]!=0){
        cell.vip_img.hidden = NO;
    }else{
        cell.vip_img.hidden = YES;
    }
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGSize size = CGSizeMake((SCRE_WIDTH-1)/2, (SCRE_WIDTH-1)/2);
    
    return size;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    if([kind isEqualToString:UICollectionElementKindSectionHeader])
    {
        UICollectionReusableView *headerView = [_collection dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerId forIndexPath:indexPath];
        if(headerView == nil)
        {
            headerView = [[UICollectionReusableView alloc] init];
        }
        headerView.backgroundColor = [UIColor clearColor];
        CGRect ad =  _adView.frame;
        ad.origin.y = 0;
        _adView.frame = ad;
        
        UIButton  *delete = [[UIButton alloc]initWithFrame:CGRectMake(SCRE_WIDTH - 40, (64/2-20), 40, 40)];
        [delete addTarget:self action:@selector(deleteAD:) forControlEvents:UIControlEventTouchUpInside];
        
        CGRect zb = _zhibView.frame;
        zb.origin.y = ad.size.height;
        _zhibView.frame = zb;
        if (isdel == 0) {
            [headerView addSubview:_adView];
        }
        [headerView addSubview:_zhibView];
        [headerView addSubview:delete];
        
        return headerView;
    }
    
    return nil;
}
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (isdel == 0) {
        return (CGSize){SCRE_WIDTH,_adView.frame.size.height+_zhibView.frame.size.height};
    }
    return (CGSize){SCRE_WIDTH,_zhibView.frame.size.height};
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    NSMutableDictionary *dic = [data objectAtIndex:indexPath.row];
    LoginResponseModel *model = [[LoginResponseModel alloc]init];
    [model serializationWithDictionary:dic];
    
    DTModel *mode = [[DTModel alloc]init];
    mode.uid = model.uid;
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    FriendDetailsMainVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"FriendDetailsMainVC"];
    searchResultDetailController.model = mode;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
#pragma mark 筛选
- (IBAction)toscreenAxtion:(UIButton *)sender {
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                 bundle:[NSBundle mainBundle]];
    UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"screenVC"];
    searchResultDetailController.view.backgroundColor = [UIColor clearColor];
    searchResultDetailController.modalPresentationStyle= UIModalPresentationOverFullScreen;
    [self presentViewController:searchResultDetailController animated:YES completion:nil];
}
#pragma mark 场景模式
- (IBAction)toSceneAction:(UIButton *)sender {
    
    NSMutableDictionary *dic = [UserDefaults readUserDefaultObjectValueForKey:@"userLocation"];
    [[BusinessService shareInstance]changjing_nearby_persons:dic success:^(id result) {
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"FJ"
                                                                     bundle:[NSBundle mainBundle]];
        SceneViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"SceneVC"];
        searchResultDetailController.ary = result;
        searchResultDetailController.isuser = YES;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    } failure:^(id result) {
        [SVProgressHUD showErrorWithStatus:result];
    }];
}
-(void)deleteAd:(NSNotificationCenter *)not {
    [self deleteAD:nil];
}
- (IBAction)deleteAD:(UIButton *)sender {
    [AppDelegate shareDelegate].isdeleteAd = YES;
    [_adView removeFromSuperview];
    
    
    //设置动画的名字
    [UIView beginAnimations: @"Animation" context: nil];
    //设置动画的开始移动位置
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置动画的间隔时间
    [UIView setAnimationDuration: 0.20];
    //设置视图移动的位移
    
    //设置动画结束
    [UIView commitAnimations];
    [_collection reloadData];
}



#pragma mark -- 懒加载
-(NSArray *)colorArr{
    if (!_colorArr) {
        _colorArr = @[@"#F0E2DD",@"#E9F2EF",@"#DDE4EF",@"#F3F0DA"];
    }
    return _colorArr;
}

@end
